import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:cave_flutter/common/chat_manager.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/routes/whl_app_pages.dart';
import 'package:cave_flutter/utils/whl_dialog_util.dart';
import 'package:cave_flutter/whl_app.dart';
import 'package:cave_flutter/pages/whl_chat/whl_chat_room/record_sheet_view/whl_record_sheet_view.dart';
import 'package:cave_flutter/pages/whl_chat/whl_chat_room/whl_chat_room_logic.dart';
import 'package:cave_flutter/pages/cave/cave_group_chat/whl_chat_group_room_logic.dart';
import 'package:cave_flutter/utils/whl_permission_util.dart';
import 'package:cave_flutter/utils/whl_rc_im_utils.dart';
import 'package:cave_flutter/utils/whl_record_voice_utils.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:cave_flutter/widgets/whl_bottom_action_sheet.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:nim_core/nim_core.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

import '../../../../common/chat_rtc_manager.dart';

enum BottomControlViewType {
  text,
  emoji,
  voice,
  redPackage,
  image,
  more,
  transfer,
  camera,
  videoChat, //
  nameCard, //名片
  file, //文件
  photo,
  collection, //收藏
  recallMsg, //双向撤回消息
  readBurn, //阅后即焚
  flashImage, //闪图
  sendVip, //赠送会员
  location, //位置
}

class ButtonModel {
  String? title;
  String? icon;
  String? activityIcon;
  Function? onTap;
  BottomControlViewType? type;

  ButtonModel(
      {this.title, this.icon, this.activityIcon, this.onTap, this.type});
}

class WhlBottomControlViewLogic extends GetxController {
  // final RCIMIWConversation conversationModel;

  TextEditingController inputTextController = TextEditingController();
  FocusNode focusNode = FocusNode();
  bool isGroup = false; //是否是群聊
  bool isShowEmoji = false;
  bool isShowVoice = false;
  bool isShowMore = false;
  bool showKeyBoard = false;
  WhlRecordVoiceUtils recordVoiceUtils = WhlRecordVoiceUtils();
  WhlChatRoomLogic roomLogic = Get.put(WhlChatRoomLogic());
  WhlChatGroupRoomLogic roomGroupLogic = Get.put(WhlChatGroupRoomLogic());

  int caveId = 0;
  String toAccountId = '';

  // WhlBottomControlViewLogic() {
  //   logic = Get.put(WhlChatRoomLogic());
  // }

  List<ButtonModel> gridItemList = [];

  @override
  void onClose() {
    recordVoiceUtils.close();
    super.onClose();
  }

  @override
  void onInit() {
    super.onInit();
    recordVoiceUtils.initRecord();
    // if (conversationModel.type == '1') {
    //   gridItemList.add(ButtonModel(title: '阅后即焚', icon: 'icon_chat_tool_read_burn.png', type: BottomControlViewType.readBurn));
    // }
  }

  @override
  void onReady() {
    super.onReady();
    if (isGroup) {
      List<ButtonModel> groupItemList = [
        ButtonModel(
            title: '相册',
            icon: 'icon_chat_tool_pic.png',
            type: BottomControlViewType.photo),
        ButtonModel(
            title: '拍摄',
            icon: 'icon_chat_tool_camera.png',
            type: BottomControlViewType.camera),
        ButtonModel(
            title: '红包',
            icon: 'icon_chat_tool_red_pkg.png',
            type: BottomControlViewType.redPackage),
        ButtonModel(
            title: '闪图',
            icon: 'icon_chat_tool_flash_image.png',
            type: BottomControlViewType.flashImage),
        ButtonModel(
            title: '位置',
            icon: 'icon_chat_tool_location.png',
            type: BottomControlViewType.location),
      ];
      gridItemList.addAll(groupItemList);
    } else {
      List<ButtonModel> singleItemList = [
        ButtonModel(
            title: '相册',
            icon: 'icon_chat_tool_pic.png',
            type: BottomControlViewType.photo),
        ButtonModel(
            title: '拍摄',
            icon: 'icon_chat_tool_camera.png',
            type: BottomControlViewType.camera),
        ButtonModel(
            title: '蜜语连线',
            icon: 'icon_chat_tool_video_chat.png',
            type: BottomControlViewType.videoChat),
        ButtonModel(
            title: '红包',
            icon: 'icon_chat_tool_red_pkg.png',
            type: BottomControlViewType.redPackage),
        ButtonModel(
            title: '闪图',
            icon: 'icon_chat_tool_flash_image.png',
            type: BottomControlViewType.flashImage),
        ButtonModel(
            title: '赠送会员',
            icon: 'icon_chat_tool_vip.png',
            type: BottomControlViewType.sendVip),
        ButtonModel(
            title: '位置',
            icon: 'icon_chat_tool_location.png',
            type: BottomControlViewType.location),
      ];
      gridItemList.addAll(singleItemList);
    }
  }

  doClickSend(String text) {
    if (text.isEmpty) {
      MyToast.show('发送消息不能为空');
      return;
    }
    inputTextController.clear();
    if (isGroup == true) {
      roomGroupLogic.createAndSendMessageModelWithData(data: text);
    } else {
      roomLogic.createAndSendMessageModelWithData(data: text);
      
    }
  }

  doClickVoiceRecord() {
    WhlPermissionUtil.reqMicrophonePermission(onSuccessAction: () {
      Get.bottomSheet(WhlRecordSheetPage(), isScrollControlled: false)
          .then((value) {
        if (value != null) {
          RecordVoiceModel model = value as RecordVoiceModel;
          if (isGroup == true) {
            roomGroupLogic.createAndSendMessageModelWithData(
              data: model.path,
              time: model.time,
              dataLength: model.size,
              type: NIMMessageType.audio);
          } else {
            roomLogic.createAndSendMessageModelWithData(
              data: model.path,
              time: model.time,
              dataLength: model.size,
              type: NIMMessageType.audio);
          }
          
        }
      });
    });
  }

  doClickFunctionBtn(ButtonModel model) async {
    if (model.type == BottomControlViewType.photo) {
      WhlPermissionUtil.reqStoragePermission(onSuccessAction: () async {
        List<AssetEntity>? assets = await AssetPicker.pickAssets(Get.context!,
            pickerConfig: const AssetPickerConfig(
              maxAssets: 9,
              requestType: RequestType.image,
            ));
        if (assets?.isNotEmpty ?? false) {
          for (var element in assets!) {
            File? file = await element.file;
            if (file != null) {
              if (isGroup == true) {
                 roomGroupLogic.createAndSendMessageModelWithData(
                  data: file.path,
                  mimeType: element.mimeType ?? "",
                  fileName: element.title ?? "",
                  size:
                      Size(element.width.toDouble(), element.height.toDouble()),
                  type: NIMMessageType.image);
              } else {
                 roomLogic.createAndSendMessageModelWithData(
                  data: file.path,
                  mimeType: element.mimeType ?? "",
                  fileName: element.title ?? "",
                  size:
                      Size(element.width.toDouble(), element.height.toDouble()),
                  type: NIMMessageType.image);
              }
             
              // WhlRCIMUtils.onSendImageMessage(conversationModel, file.path);
            }
          }
        }
      });
    } else if (model.type == BottomControlViewType.file) {
      WhlPermissionUtil.reqStoragePermission(onSuccessAction: () async {
        FilePickerResult? result = await FilePicker.platform.pickFiles();
        if (result != null) {
          File file = File(result.files.single.path!);
          // WhlRCIMUtils.onSendFileMessage(conversationModel, file.path);
        }
      });
    } else if (model.type == BottomControlViewType.redPackage) {
      if (isGroup == true) {
        Get.toNamed(Routes.caveRedEnvelopePage, arguments: {
          'caveId': caveId,
        });
      } else {
        Get.toNamed(Routes.sendRedGroup);
      }
    } else if (model.type == BottomControlViewType.location) {
      WhlBottomActionSheet.show(['发送位置', '共享实时位置'], callBack: (index) {
        if (index == 0) {
          // Get.toNamed(Routes.sendLocation);
        } else {
          // Get.toNamed(Routes.shareLocation);
        }
      });
    } else if (model.type == BottomControlViewType.camera) {
      final AssetEntity? asset = await CameraPicker.pickFromCamera(
        Get.context!,
        pickerConfig: const CameraPickerConfig(),
      );
      if (asset != null) {
        File? file = await asset.file;
        savePhoto(file);
        if (isGroup == true) {
        roomGroupLogic.createAndSendMessageModelWithData(
            data: file?.path ?? "",
            mimeType: asset.mimeType ?? "",
            fileName: asset.title ?? "",
            size: Size(asset.width.toDouble(), asset.height.toDouble()),
            type: NIMMessageType.image);
        } else {
          roomLogic.createAndSendMessageModelWithData(
            data: file?.path ?? "",
            mimeType: asset.mimeType ?? "",
            fileName: asset.title ?? "",
            size: Size(asset.width.toDouble(), asset.height.toDouble()),
            type: NIMMessageType.image);
        }
        
      };
    } else if (model.type == BottomControlViewType.videoChat) {
      WhlBottomActionSheet.show(['语音通话 ', '视频通话 '], callBack: (index) {
        _startVideoCalling(Get.context!, isVideoCall: index == 1);
        // if (index == 0) {
        //   Get.toNamed(Routes.chatCallPage);
        // } else {
        //   Get.toNamed(Routes.chatCallPage);
        // }
      });
    }
  }

  Future<void> _startVideoCalling(BuildContext context,
      {bool isVideoCall = false}) async {
    //检查权限
    final permissions = [Permission.camera, Permission.microphone];
    if (Platform.isAndroid) {
      permissions.add(Permission.storage);
    }
    List<Permission> missed = [];
    for (var permission in permissions) {
      PermissionStatus status = await permission.status;
      if (status != PermissionStatus.granted) {
        missed.add(permission);
      }
    }

    bool allGranted = missed.isEmpty;
    if (!allGranted) {
      List<Permission> showRationale = [];
      for (var permission in missed) {
        bool isShown = await permission.shouldShowRequestRationale;
        if (isShown) {
          showRationale.add(permission);
        }
      }

      if (showRationale.isNotEmpty) {
        WhlDialogUtil.showConfirmDialog('您需要允许一些权限',
            isShowCancel: true, cancelAction: () {
          // Get.back();
        }, sureAction: () async {
          // Get.back();
          Map<Permission, PermissionStatus> allStatus = await missed.request();
          allGranted = true;
          for (var status in allStatus.values) {
            if (status != PermissionStatus.granted) {
              allGranted = false;
            }
          }
        });
      } else {
        Map<Permission, PermissionStatus> allStatus = await missed.request();
        allGranted = true;
        for (var status in allStatus.values) {
          if (status != PermissionStatus.granted) {
            allGranted = false;
          }
        }
      }
    }
    if (allGranted) {
      String roomName = "$toAccountId&${ChatManager.getInstance().getImAccountId()}";
      getRTCToken(roomName,isVideoCall: isVideoCall,toAccountId: toAccountId,userModel: roomLogic.userModel);
    }
    // Get.to(VideoPage(cid: "123", uid: 1234));
    // Get.toNamed(Routes.chatCallIngPage);
    // Get.toNamed(Routes.chatCallPage);
  }

  void savePhoto(File? file) async {
    if (file == null) {
      return;
    }
    bool permission = await getPermission();
    // var status = await Permission.photos.status;
    if (permission) {
      Uint8List? fixedImageBytes = await FlutterImageCompress.compressWithFile(
        file.path,
        rotate: 0,
        quality: 100,
        keepExif: false,
        autoCorrectionAngle: true,
      );
      if (fixedImageBytes != null) {
        final result = await ImageGallerySaver.saveImage(fixedImageBytes!,
            quality: 60, isReturnImagePathOfIOS: Platform.isIOS);
        if (result != null) {
          print("save success");
        }
      }
    } else {
      // savePhoto();
    }
  }

  Future<bool> getPermission() async {
    if (Platform.isIOS) {
      var status = await Permission.photos.status;
      if (status.isDenied) {
        Map<Permission, PermissionStatus> statuses = await [
          Permission.photos,
        ].request();
      }
      return status.isGranted;
    } else {
      var status = await Permission.storage.status;
      if (status.isDenied) {
        Map<Permission, PermissionStatus> statuses = await [
          Permission.storage,
          // Permission.photos,
        ].request();
      }
      return status.isGranted;
    }
  }

  doClickMore() {
    isShowMore = !isShowMore;
    isShowVoice = false;
    hideKeyboard(Get.context);
    isShowEmoji = false;
    update();
  }

  doClickEmoji() {
    isShowEmoji = !isShowEmoji;
    isShowVoice = false;
    hideKeyboard(Get.context);
    isShowMore = false;
    update();
  }

  resetAllStatus() {
    isShowEmoji = false;
    isShowVoice = false;
    isShowMore = false;
    hideKeyboard(Get.context);
    update();
  }

}
